﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ASBCC.Business;

namespace ASB.CC.Web.UserControls
{
    public partial class Pager : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            GetHost().DataBound += Host_DataBound;
        }

        private void Host_DataBound(object sender, EventArgs e)
        {
            // always show pager
            // http://www.ryanmcdonnell.com/always-show-the-pagertemplate-in-gridview-control/
            (sender as GridView).BottomPagerRow.CssClass = "pager-row";
            (sender as GridView).BottomPagerRow.Visible = true;
        }

        protected override void OnPreRender(EventArgs e)
        {
            // disable some buttons
            int current = GetCurrentPage();
            int total = GetTotalPages();

            btnFirst.Enabled = current != 1;
            btnPrev.Enabled = current != 1;
            btnNext.Enabled = current != total;
            btnLast.Enabled = current != total;

            btnFirst.CssClass = btnFirst.Enabled ? "pager-first" : "pager-first-disabled";
            btnPrev.CssClass = btnPrev.Enabled ? "pager-prev" : "pager-prev-disabled";
            btnNext.CssClass = btnNext.Enabled ? "pager-next" : "pager-next-disabled";
            btnLast.CssClass = btnLast.Enabled ? "pager-last" : "pager-last-disabled";

            base.OnPreRender(e);
        }

        protected int GetTotalRecords()
        {
            return (Page as EntityPage).TotalRowCount;
        }

        protected int GetCurrentPage()
        {
            return GetHost().PageIndex + 1;
        }
        protected int GetTotalPages()
        {
            return GetHost().PageCount;
        }

        protected void BtnGo_Click(object sender, EventArgs e)
        {
            LinkButton btnGo = sender as LinkButton;
            int index;

            if (int.TryParse(txtPage.Text, out index))
            {
                if (index > GetTotalPages())
                    btnGo.CommandArgument = GetTotalPages().ToString();
                else if (index < 1)
                    btnGo.CommandArgument = "1";
                else
                    btnGo.CommandArgument = index.ToString();
            }
            else
            {
                btnGo.CommandArgument = "1";
            }
        }

        private GridView GetHost()
        {
            return this.Parent.Parent.Parent.Parent as GridView;
        }
    }
}